/*
 * Copyright (c) jiucheng.org
 */
package org.jiucheng.template;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.jiucheng.template.function.Sys;
import org.jiucheng.template.grammar.For;
import org.jiucheng.template.grammar.Grammar;
import org.jiucheng.template.grammar.GrammarFile;
import org.jiucheng.template.grammar.If;
import org.jiucheng.template.grammar.Include;
import org.jiucheng.template.grammar.Print;
import org.jiucheng.template.grammar.Println;
import org.jiucheng.template.grammar.Root;

/**
 * 
 * @author jiucheng
 *
 */
public class GrammarManager {

    public static final String B_OCT = "<#";
    public static final String E_OCT = "#>";

    private Map<String, Class<?>> funces = new ConcurrentHashMap<String, Class<?>>();
    private GrammarContent grammarContent = new FileGrammarContent();

    public GrammarManager() {
        putClass("sys", Sys.class);
    }

    public void setGrammarContent(GrammarContent grammarContent) {
        this.grammarContent = grammarContent;
    }

    public void putClass(String alia, Class<?> clazz) {
        if (alia == null || alia.trim().length() == 0) {
            throw new IllegalArgumentException("alia can't is null");
        }
        if (clazz == null) {
            throw new NullPointerException();
        }
        funces.put(alia, clazz);
    }

    public Class<?> getClass(String alia) {
        if (alia == null || alia.trim().length() == 0) {
            throw new IllegalArgumentException("alia can't is null");
        }
        return funces.get(alia);
    }

    public Root parse(String filePath) {
        Root root = new Root();
        root.setFile(filePath);
        List<String> list = grammarContent.read(filePath);
        if (list != null && list.size() > 0) {
            translate(list);
            root.addAll(parse(root, list));
        }
        return root;
    }

    private List<Grammar> parse(GrammarFile grammarFile, List<String> list) {
        List<Grammar> root = new ArrayList<Grammar>();
        String val;
        int index = 0;
        int bf = 0;
        int ef;
        boolean isFor = false;
        boolean isIf = false;
        for (int i = 0; i < list.size(); i++) {
            val = list.get(i).trim();
            if (val.startsWith(For.FOR)) {
                if (!isIf) {
                    isFor = true;
                    index++;
                    if (index == 1) {
                        bf = i;
                    }
                    continue;
                }
            } else if (val.startsWith(For.ROF)) {
                if (isFor) {
                    index--;
                    if (index == 0) {
                        ef = i;
                        root.add(getFor(grammarFile, list.subList(bf, ef + 1)));
                        isFor = false;
                        continue;
                    }
                }
            } else if (val.startsWith(If.IF)) {
                if (!isFor) {
                    isIf = true;
                    index++;
                    if (index == 1) {
                        bf = i;
                    }
                    continue;
                }
            } else if (val.startsWith(If.FI)) {
                if (isIf) {
                    index--;
                    if (index == 0) {
                        ef = i;
                        root.add(getIf(grammarFile, list.subList(bf, ef + 1)));
                        isIf = false;
                        continue;
                    }
                }
            }
            if (index == 0) {
                Grammar g = getGrammar(grammarFile, val);
                if (g != null) {
                    root.add(g);
                }
            }
        }
        return root;
    }

    private For getFor(GrammarFile grammarFile, List<String> vals) {
        For f = new For(vals.get(0));
        String val;
        int b = 0;
        boolean isFor = false;
        boolean isIf = false;
        int index = 0;
        for (int i = 1; i < vals.size(); i++) {
            val = vals.get(i).trim();
            if (val.startsWith(For.FOR)) {
                if (isFor) {
                    index++;
                }
                if (!isFor && !isIf) {
                    isFor = true;
                    b = i;
                    index = 1;
                    continue;
                }
            } else if (val.startsWith(For.ROF)) {
                index--;
                if (isFor && index == 0) {
                    isFor = false;
                    f.add(getFor(grammarFile, vals.subList(b, i + 1)));
                    continue;
                }
            } else if (val.startsWith(If.IF)) {
                if (isIf) {
                    index++;
                }
                if (!isIf && !isFor) {
                    isIf = true;
                    b = i;
                    index = 1;
                    continue;
                }
            } else if (val.startsWith(If.FI)) {
                index--;
                if (isIf && index == 0) {
                    isIf = false;
                    f.add(getIf(grammarFile, vals.subList(b, i + 1)));
                    continue;
                }
            }
            if (!isFor && !isIf) {
                Grammar g = getGrammar(grammarFile, val);
                if (g != null) {
                    f.add(g);
                }
            }
        }
        return f;
    }

    private If getIf(GrammarFile grammarFile, List<String> vals) {
        String h = vals.get(0);
        If f = new If(h);
        String val;
        boolean isIf = false;
        boolean isElseif = false;
        boolean isElse = false;
        int b = 0;
        boolean isFor = false;
        int index = 0;
        for (int i = 1; i < vals.size(); i++) {
            val = vals.get(i).trim();
            if (val.startsWith(If.IF)) {
                if (isIf) {
                    index++;
                }
                if (!isIf && !isFor) {
                    isIf = true;
                    b = i;
                    index = 1;
                    continue;
                }
            } else if (val.startsWith(If.ELSEIF)) {
                if (isIf || isFor) {
                    continue;
                }
                isElseif = true;
                isElse = false;
                f.addElseifHeader(val);
                continue;
            } else if (val.startsWith(If.ELSE)) {
                if (isIf || isFor) {
                    continue;
                }
                isElse = true;
                isElseif = false;
                continue;
            } else if (val.startsWith(If.FI)) {
                index--;
                if (isIf && index == 0) {
                    isIf = false;
                    List<String> vals1 = vals.subList(b, i + 1);
                    if (vals1.size() > 0) {
                        If f1 = getIf(grammarFile, vals1);
                        if (isElseif) {
                            f.addElseifG(f1);
                        } else if (isElse) {
                            f.addElse(f1);
                        } else {
                            f.addIf(f1);
                        }
                    }
                    continue;
                }
            } else if (val.startsWith(For.FOR)) {
                if (isFor) {
                    index++;
                }
                if (!isIf && !isFor) {
                    isFor = true;
                    b = i;
                    index = 1;
                    continue;
                }
            } else if (val.startsWith(For.ROF)) {
                index--;
                if (isFor && index == 0) {
                    isFor = false;
                    For rof = getFor(grammarFile, vals.subList(b, i + 1));
                    if (isElseif) {
                        f.addElseifG(rof);
                    } else if (isElse) {
                        f.addElse(rof);
                    } else {
                        f.addIf(rof);
                    }
                    continue;
                }
            }
            if (!isIf && !isFor) {
                Grammar g = getGrammar(grammarFile, val);
                if (g != null) {
                    if (isElseif) {
                        f.addElseifG(g);
                    } else if (isElse) {
                        f.addElse(g);
                    } else {
                        f.addIf(g);
                    }
                }
            }
        }
        return f;
    }

    // 返回单行命令
    private Grammar getGrammar(GrammarFile grammarFile, String val) {
        if (val.startsWith("println")) {
            Grammar g = new Println(new String[] { val.substring(val.indexOf("\"") + 1, val.lastIndexOf("\"")) });
            return g;
        } else if (val.startsWith("print")) {
            Grammar g = new Print(new String[] { val.substring(val.indexOf("\"") + 1, val.lastIndexOf("\"")) });
            return g;
        } else if (val.startsWith("include")) {
            Include g = new Include(val.substring(val.indexOf("\"") + 1, val.lastIndexOf("\"")));
            g.setGrammarFile(grammarFile);
            g.setGrammarManager(this);
            return g;
        }
        return null;
    }

    private void translate(List<String> list) {
        String val;
        boolean e = false;
        for (int i = list.size() - 1; i > -1; i--) {
            val = list.get(i);
            if (!e) {
                if (E_OCT.equals(val.trim())) {
                    e = true;
                    list.remove(i);
                    continue;
                }
                list.set(i, MessageFormat.format(" println \"{0}\";", val));
            } else {
                val = val.trim();
                if (B_OCT.equals(val)) {
                    e = false;
                    list.remove(i);
                } else if (val.startsWith("//")) {
                    list.remove(i);
                }
            }
        }
    }
}
